package com.socialcoco.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.socialcoco.VO.SocialUser;
import com.socialcoco.VO.telUserVo;
import com.socialcoco.bean.user;
import com.socialcoco.contant.AuthServerConstant;
import com.socialcoco.entity.*;
import com.socialcoco.exception.myExection;
import com.socialcoco.mapper.DiaryResMapper;
import com.socialcoco.respone.BaseResponse;
import com.socialcoco.respone.ResultUtils;
import com.socialcoco.respone.resultenum;
import com.socialcoco.service.ILikeService;
import com.socialcoco.serviceImpl.*;
import com.socialcoco.util.SmsUtils;
import com.socialcoco.util.md5;
import com.socialcoco.util.verify;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jsoup.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 赵志浩
 * @since 2022-03-17 09:16:50
 */
@Slf4j
@RestController
@RequestMapping("/socialcoco/user")
public class UserController {

    /**
     * 注册用户
     */
    @Autowired
    private ShiroServiceImpl shiroService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private DiaryResMapper diaryResMapper;
    @Autowired
    private UserFriendServiceImpl userFriendService;
    @Autowired
    private ILikeServiceImpl iLikeService;
    @Autowired
    private DiaryServiceImpl diaryService;
    @Autowired
    private signUpServiceImpl signUpService;
    @Autowired
    private EpidemicSituationServiceImpl epidemicSituationService;
    @Autowired
    private DiaryResServiceImpl diaryResService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private LoginServiceImpl loginService;
    @PostMapping("/enroll")
    @ApiOperation("用户注册自己的账号")
    public BaseResponse<Object> enroll(@RequestBody User u){
        verify v=new verify();
        boolean nameFlag=false;
        boolean emailFlag=false;
        boolean pwdFlag=false;
        if(u==null) return null;
        else{
            if(v.checkName(u.getUsername())){
                HashMap map=new HashMap();
                map.put("username",u.getUsername());
                List list = userService.listByMap(map);
                if(list.size()==0&&v.checkName(u.getUsername())){
                    nameFlag=true;
                }
            }
            if(v.checkEmail(u.getEmail())){
                HashMap map=new HashMap();
                map.put("email",u.getEmail());
                List list = userService.listByMap(map);
                if(list.size()==0&&v.checkEmail(u.getEmail())){
                    emailFlag=true;
                }
            }
        }
        md5 encrypt=new md5();
        if(emailFlag==true&&nameFlag==true){
            u.setActive(1);
            String password = encrypt.inputPassTo(u.getPassword());
            u.setPassword(password);
            u.setSalt("1a2b3c4d");
            u.setCreateTime(new Date());
            u.setHeadimgae("http://182.92.64.139:9000/movies/head.jpg");//默认头像
            userService.save(u);
            return ResultUtils.success("注册成功");
        }
        return ResultUtils.error(50000,"检查输入的内容，注册错误！");
    }
    @GetMapping("checkName/{username}")
    @ApiOperation("检查用户注册的账号是否存在")
    public BaseResponse<Object> checkName(@PathVariable String username){
        log.info("zzz"+username);
        System.out.println();
        verify v=new verify();
        if(!v.checkName(username))return ResultUtils.error(resultenum.CHECK_FORMAT.getCode(), resultenum.CHECK_FORMAT.getMsg());
        HashMap map=new HashMap();
        map.put("username",username);
        List list = userService.listByMap(map);
        if(list.size()==0&&v.checkName(username)){
            return ResultUtils.success(resultenum.CHECK_NULL);
        }
        return ResultUtils.error(11111,"用户名已经存在");
    }
    @GetMapping("checkEmail/{email}")
    @ApiOperation("检查用户注册的email是否存在")
    public BaseResponse<Object> checkEmail(@PathVariable String email){
        verify v=new verify();
        if(!v.checkEmail(email))
        return ResultUtils.error(resultenum.CHECK_FORMAT.getCode(), resultenum.CHECK_FORMAT.getMsg());
        HashMap map=new HashMap();
        map.put("email",email);
        List list = userService.listByMap(map);
        if(list.size()==0&&v.checkEmail(email)){
            return ResultUtils.success(resultenum.CHECK_NULL);
        }
        return ResultUtils.error(11111,"邮箱已经存在");
    }
    @GetMapping("checkPassword/{password}")
    @ApiOperation("检查用户密码")
    public BaseResponse<Object> checkPassword(@PathVariable String password){
        verify v=new verify();
        if(v.checkPwd(password))
            return ResultUtils.success("符合要求");
        return ResultUtils.error(resultenum.CHECK_FORMAT.getCode(),resultenum.CHECK_FORMAT.getMsg());
    }
    /**
     * 用户登录，通过shiro框架，生成暂时的token
     */
    @PostMapping("/login")
    public BaseResponse<Object> login(@RequestBody User user){
        User byUsername = shiroService.findByUsername(user.getUsername());
        md5 md5 = new md5();
        String s = md5.fromPassTo(user.getPassword());
        Map result=new HashMap();
        if (byUsername == null || !byUsername.getPassword().equals(s)) {
            result.put("status", 400);
            result.put("msg", "账号或密码有误");
            return ResultUtils.success(result);
        }
        else {
            result = shiroService.createToken(byUsername.getUid());
            result.put("status", 200);
            result.put("msg", "登陆成功");
            result.put("data",byUsername);
            return ResultUtils.success(result);
        }
    }
    /**
     * 发送验证码
     */
    @GetMapping("/sms/{telNumber}")
    public BaseResponse<Object> login(@PathVariable String telNumber){
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + telNumber);
        if(!StringUtils.isEmpty(redisCode)){
            long currentTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - currentTime < 60000){
                return ResultUtils.error(30000,"请勿重复发送。");
            }

        }
        String param=(int)((Math.random()*9+1)*100000)+"";
        String redisCodes=param+"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+telNumber,redisCodes,10, TimeUnit.MINUTES);
        SmsSingleSenderResult result2 = SmsUtils.sendCode(telNumber, "+86", param);
        JSONObject resultObject = JSONObject.parseObject(String.valueOf(result2));
        String msg = resultObject.getString("errmsg");
        return ResultUtils.success(msg);
    }
    /**
     * 用户手机号登录
     */
    @PostMapping("sms/login")
        public BaseResponse<Object> login(@RequestBody telUserVo telUserVo){

        String redisCode= redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + telUserVo.getPhone());
        Map result=new HashMap();
        if(!StringUtils.isEmpty(redisCode)){
            if(telUserVo.getCode().equals(redisCode.split("_")[0])){
                //删除redis验证码

                User user = loginService.telLogin(telUserVo);
                if (user == null) {
                    result.put("status", 400);
                    result.put("msg", "账号或密码有误");
                    return ResultUtils.success(result);
                }
                else {
                    result = shiroService.createToken(user.getUid());
                    result.put("status", 200);
                    result.put("msg", "登陆成功");
                    result.put("data",user);
                    redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX+telUserVo.getPhone());
                    return ResultUtils.success(result);
                }


        }

    }
        result.put("status", 409);
        result.put("msg", "验证码错误");
        return ResultUtils.success(result);
    }
    /**
     * 用户微博登录
     */
    @PostMapping("sms/OAuth/login/success")
    public BaseResponse<Object> weibo(@RequestBody SocialUser socialUser) {
        Map result=new HashMap();
        User user = loginService.weiboLogin(socialUser);
        if (user == null) {
            result.put("status", 400);
            result.put("msg", "账号或密码有误");
            return ResultUtils.success(result);
        }
        else {
            result = shiroService.createToken(user.getUid());
            result.put("status", 200);
            result.put("msg", "登陆成功");
            result.put("data",user);
            return ResultUtils.success(result);
        }

    }


    /**
     * 获取用户的关注有那些
     */
    @GetMapping("/care/{uid}")
    public BaseResponse<Object> care(@PathVariable Integer uid,@RequestHeader("token")String token){
        List<User> users = diaryResMapper.listFriend(uid);
        if(uid==null||uid<0){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        return ResultUtils.success(users);
    }

    /**
     * 判断用户是否关注
     * @param uid 用户的id
     * @param uidto 用户点击某个博主的id
     * @param token
     * @return
     */
    @ApiOperation("获取用户是否关注")
    @GetMapping("/isCare/{uid}/{uidto}")
    public BaseResponse<Object> isCare(@PathVariable Integer uid,@PathVariable Integer uidto,@RequestHeader("token")String token){
        QueryWrapper<UserFriend> UserFriendList=new QueryWrapper<>();
        UserFriendList.eq("user_id",uid).eq("friend_id",uidto);
        List<UserFriend> list = userFriendService.list(UserFriendList);
        if(list.size()==0){
            return ResultUtils.success("careNo");
        }
        return ResultUtils.success("careOk");
    }
    @ApiOperation("用户关注某博主")
    @PostMapping("/SaveCare")
    public BaseResponse<Object> SaveCare(@RequestBody UserFriend userFriend,@RequestHeader("token")String token){
        log.info(userFriend.toString());

        if(userFriend==null){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        userFriendService.save(userFriend);
        return ResultUtils.success("saveOk");
    }
    @ApiOperation("用户取消关注")
    @GetMapping("/NoCare/{uid}/{uidto}")
    public BaseResponse<Object> NoCare(@PathVariable Integer uid,@PathVariable Integer uidto,@RequestHeader("token")String token){
        QueryWrapper<UserFriend> UserFriendList=new QueryWrapper<>();
        UserFriendList.eq("user_id",uid).eq("friend_id",uidto);
        boolean remove = userFriendService.remove(UserFriendList);
        if(remove){
            return ResultUtils.success("Pickup");//取关成功
        }
        return ResultUtils.success("PickupNo");//取关失败
    }
    @ApiOperation("获取用户所有博客点赞粉丝的数量")
    @GetMapping("/likeNum/{uid}")
    public BaseResponse<Object> rank(@RequestHeader("token") String token, @PathVariable String uid){
        Map<String, Object> Map = new HashMap<>();

        QueryWrapper<ILike> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("uid",uid);
        QueryWrapper<UserFriend> queryWrapper1=new QueryWrapper<>();
        queryWrapper1.eq("user_id",uid);
        QueryWrapper<UserFriend> queryWrapper2=new QueryWrapper<>();
        queryWrapper2.eq("friend_id",uid);
        long count = diaryResService.like(Integer.valueOf(uid));
        log.info(String.valueOf(count));
        List<ILike> list = iLikeService.list(queryWrapper);
        List<UserFriend> list1 = userFriendService.list(queryWrapper1);
        List<UserFriend> list2 = userFriendService.list(queryWrapper2);
        Map.put("like",count);
        Map.put("care",list1);
        Map.put("fan",list2);
        return  ResultUtils.success(Map);
    }
    @ApiOperation("用户报名社团")
    @PostMapping("/signUp")
    public BaseResponse<Object> signUp(@RequestHeader("token") String token, @RequestBody signUp signUp){
        if(signUp==null){
            throw new myExection(resultenum.BODY_NULL.getCode(),resultenum.BODY_NULL.getMsg());
        }
        signUp.setCreateTime(new Date());
        signUpService.save(signUp);
        return ResultUtils.success("signOk");
    }
    @ApiOperation("查看用户是否报名")
    @PostMapping("/isSignUp/{uid}")
    public BaseResponse<Object> isSignUp(@RequestHeader("token") String token,@PathVariable String uid,  @RequestBody List<DiaryRespone> temp){
        temp.remove(0);
        for (int i = 0; i < temp.size(); i++) {
        try {
            QueryWrapper<signUp> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("uid", uid).eq("did", temp.get(i).getId());
            List<signUp> list = signUpService.list(queryWrapper);
            if (list.size() > 0) {
                temp.get(i).setIsSign(0);
            }
        }catch (NullPointerException e){
            return ResultUtils.success(temp);
            }
        }
        return ResultUtils.success(temp);
    }
    @ApiOperation("用户取消报名")
    @GetMapping("/NoSignUp/{uid}/{did}")
    public BaseResponse<Object> NoSignUp(@RequestHeader("token") String token, @PathVariable String uid,@PathVariable String did){
        QueryWrapper<signUp> signUpQueryWrapper=new QueryWrapper<>();
        signUpQueryWrapper.eq("uid",uid).eq("did",did);
        signUpService.remove(signUpQueryWrapper);
        return ResultUtils.success("deletedOk");
    }

}

